<?php
namespace app\common\logic;

use app\common\error\Base as BaseError;

/**
 * 系统通用服务层
 */
class BaseLogic{
    //TODO:后期可添加一个单例模式或者使用app()常驻
    /**
     * 参数错误返回原因
     * @param  [type] $error [description]
     * @return [type]        [description]
     */
    protected static function paramSceneCheck($object, $scene, $param){

        $validate_res = $object->scene($scene)->check($param);

        if (!$validate_res) {

            $errorMsg = BaseError::$WrongRequestParam;

            $errorMsg[RESULT_MESSAGE] = $object->getError();

            self::ResponseData($errorMsg,false);
        }

    }

    /**
     * 中断并返回http协议错误
     * @param string $code [description]
     * @return [type]       [description]
     */
    protected static function throwHttpCode($code_data = [],$code = ''){

        $error = $code_data[RESULT_MESSAGE] ?: 'success';

        header("HTTP/1.1 " . $code_data[RESULT_CODE] . " " . $error);

        header("Content-Type:application/json;charset=utf-8");

        exit(json_encode($code_data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 中断并返回数据
     * @param $code_data 返回数据
     * @param bool $isHttpCode 默认不按照状态码返回,
     */
    public static function responseData($code_data,$isHttpCode = false){

        $isHttpCode && self::throwHttpCode($code_data);

        return throw_response_exception($code_data);

    }

    /**
     * 系统抛出异常
     * @param string $code
     * @param string $msg
     */
    protected static function abortException($code = 500,$msg = 'exception error'){

        abort($code, $msg);

    }

    /**
     * 魔术方法
     * @param $name
     * @param $args
     * @return object|\think\App
     */
    public static function __callStatic($name,$args){

        $layer = self::getLayerPrefix($name);

        empty($layer) && abort(403,LAYER_LOGIC_NAME.'层中魔术方法使用前缀错误');

        $instanceName = $args[0];

        $instance = parseClass($instanceName,$layer);

        return app($instance);

    }


    /**
     * 获取前缀
     * @param $name
     * @return bool|mixed
     */
    public static function getLayerPrefix($name){

        $layer = false;

        $layer_array = [LAYER_MODEL_NAME, LAYER_VALIDATE_NAME,LAYER_LOGIC_NAME,LAYER_SERVICE_NAME];

        foreach ($layer_array as $v) {

            if (strpos($name,$v) !== false) {

                $layer = $v;

                break;

            }

        }

        return $layer;

    }

}
